const db = require('../config/db');
const schedule = require('node-schedule');

// 每天凌晨执行
schedule.scheduleJob('0 0 * * *', async () => {
  try {
    const now = new Date();
    
    // 更新过期日程状态
    await db.execute(
      `UPDATE events 
       SET status = 'expired' 
       WHERE status = 'ongoing' 
       AND end_date < ?`,
      [now]
    );

    // 删除14天前的已完成或已过期日程
    const fourteenDaysAgo = new Date(now - 14 * 24 * 60 * 60 * 1000);
    await db.execute(
      `DELETE FROM events 
       WHERE (status = 'finished' OR status = 'expired') 
       AND end_date < ?`,
      [fourteenDaysAgo]
    );
  } catch (error) {
    console.error('更新日程状态失败:', error);
  }
});